package com.hdcx.Minfresh.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.activity.MainActivity;
import com.hdcx.Minfresh.activity.OrderUploadActivity;
import com.hdcx.Minfresh.adapter.ShoppingCartAdapter;
import com.hdcx.Minfresh.bean.CartWrapper;
import com.hdcx.Minfresh.bean.GoodListWrapper;
import com.hdcx.Minfresh.model.ShoppingCar;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.util.GsonUtils;
import com.hdcx.Minfresh.util.ShpfUtil;
import com.hdcx.Minfresh.view.FullyLinearLayoutManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/9.
 */

public class ShoppingCartFragment extends BaseFragment {
    private ShoppingCartAdapter adapter;
    private RecyclerView recycler;
    public ImageView img_totle;
    Boolean select_all = true;
    LinearLayout layout_submit;
    public Button bt_go;
    public TextView tv_totle_money;
    public  TextView right;
    private ShoppingCar mShoppingCar;
    private View mRelaHas;
    private View mRelaHasNothing;

    @Override
    public int getLayout() {
        return R.layout.activity_shoppingcart;
    }

    @Override
    public void initView(View view) {
        mRelaHas = view.findViewById(R.id.relaHas);
        mRelaHasNothing = view.findViewById(R.id.relaHasNothing);
        view.findViewById(R.id.buttonGoShop).setOnClickListener(this);
        recycler = (RecyclerView) view.findViewById(R.id.recycler);
        img_totle = (ImageView) view.findViewById(R.id.img_totle);
        layout_submit = (LinearLayout) view.findViewById(R.id.layout_submit);
        layout_submit.setOnClickListener(this);
        view.findViewById(R.id.tv_left).setVisibility(View.GONE);
        TextView title = (TextView) view.findViewById(R.id.tv_title);
        tv_totle_money = (TextView) view.findViewById(R.id.tv_totle_money);
        title.setText("购物车");
        right = (TextView) view.findViewById(R.id.tv_right);
        right.setText("清除");
        bt_go = (Button) view.findViewById(R.id.bt_go);

    }

    @Override
    public void initData() {
        adapter = new ShoppingCartAdapter(getActivity(), this);
        recycler.setLayoutManager(new FullyLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recycler.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        if (AppUtil.need_to_login(getActivity())) {
            return;
        } else {
            CartWrapper cartData = AppUtil.getCartData();
            //adapter.setData(cartData);
            adapter.setSharepData(cartData);
            if (cartData != null && cartData.carts.size() != 0) {
//                layout_submit.setVisibility(View.VISIBLE);
                mRelaHas.setVisibility(View.VISIBLE);
                mRelaHasNothing.setVisibility(View.GONE);
                post_main(cartData.carts);
            } else {
//                layout_submit.setVisibility(View.GONE);
                mRelaHas.setVisibility(View.GONE);
                mRelaHasNothing.setVisibility(View.VISIBLE);
            }
        }
    }

    private void post_main(List<CartWrapper.Cart> carts) {
        AppUtil.showLoading(getActivity());
        JSONObject json = new JSONObject();
        JSONArray jsonarray = new JSONArray();
        try {
            for (int i = 0; i < carts.size(); i++) {
                JSONObject json1 = new JSONObject();
                json1.put("id", carts.get(i).id);
                json1.put("ps", "0");
                json1.put("is_score", "");
                jsonarray.put(json1);
            }
            json.put("list", jsonarray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.GETGOODS)
                .content(json.toString())
                .build()
                .execute(new Callback<GoodListWrapper>() {
                    @Override
                    public GoodListWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("ShoppingCartFragment", "ShoppingCartFragment--parseNetworkResponse--"+json);
                        mShoppingCar = GsonUtils.parseJSON(json, ShoppingCar.class);
                        return new Gson().fromJson(json, GoodListWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.i("Exception", "onError: "+e);
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(GoodListWrapper response) {
                        AppUtil.closeLoading();
                        adapter.setData(response,mShoppingCar);
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_submit:
                select_all = !select_all;
                adapter.changeSelectAll(select_all);
                break;
            case R.id.buttonGoShop:
                ((MainActivity)getActivity()).toMainFragment();
                break;
        }
    }

    @Override
    public void onMyItemClick() {
        getData();
    }

    @Override
    public void onMyItemClick(Object data) {
        if(data==null){
            return;
        }
        GoodListWrapper updata  = (GoodListWrapper)data;
        post_order(updata);
    }
   /* 参数
            uid		//用户id 20
    ps		// 可选 默认0明日配送   1  后天配送  2 大后台配送
            list[
    {
        id:1,   //产品id
                quantity:5	//数量
    },
    {
        id:2,
                quantity:6
    }
    ]*/

    private void post_order(GoodListWrapper updata) {
        AppUtil.showLoading(getActivity());
        JSONObject json = new JSONObject();
        JSONArray jsonarray = new JSONArray();
        try {
            CartWrapper cartWrapper = new CartWrapper();
            for (int i = 0; i < updata.getList().size(); i++) {
                if(updata.getList().get(i).getIs_select()){
                    JSONObject json1 = new JSONObject();
                    json1.put("id", updata.getList().get(i).getId());
                    json1.put("quantity",updata.getList().get(i).getRealy_quantity());
                    json.put("ps", updata.getList().get(i).getPs());
                    jsonarray.put(json1);
                }else{
                  cartWrapper.setData(updata.getList().get(i).getId(),updata.getList().get(i).getRealy_quantity(),updata.getList().get(i).getPs(),0,0);
                }
            }
            if(cartWrapper.carts.size()==0){
                ShpfUtil.remove(AppUtil.getUserId());
            }else{
                ShpfUtil.remove(AppUtil.getUserId());
                ShpfUtil.setObject(AppUtil.getUserId(),cartWrapper);
            }
            json.put("list", jsonarray);
            json.put("uid", AppUtil.getUserId());
            json.put("version", AppUtil.getAppVersion());
            json.put("model", android.os.Build.MODEL);
            json.put("sdk", android.os.Build.VERSION.RELEASE);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.USERORDER)
                .content(json.toString())
                .build()
                .execute(new Callback<GoodListWrapper>() {
                    @Override
                    public GoodListWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, GoodListWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.i("Exception", "onError: "+e);
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(GoodListWrapper response) {
                        AppUtil.closeLoading();
                   if(response.getStatus()==1){
                       adapter.removeAndNoti();
                       AppUtil.setMain_Cart();
                       AppUtil.is_fresh=true;
                       Intent intent =new Intent(getActivity(), OrderUploadActivity.class);
                       intent.putExtra("id",response.getOrder_id());
                       getActivity().startActivity(intent);

                   }
                    }
                });
    }
}
